package org.budo.support.ehcache.util;

import java.io.Serializable;

import org.budo.support.lang.util.StringUtil;
import org.budo.support.slf4j.Slf4j;
import org.budo.support.spring.context.aware.BudoApplicationContextAware;
import org.slf4j.Logger;
import org.springframework.context.ApplicationContext;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;

/**
 * @author lmw
 */
public class EhcacheUtil {
    private static final Logger log = Slf4j.getLogger();

    public static Boolean cacheRemove(CacheManager cacheManager, String cacheName, Serializable cacheKey) {
        if (null == cacheManager || StringUtil.isEmpty(cacheName) || null == cacheKey) {
            log.error("#19 cacheRemove error, cacheManager=" + cacheManager + ", cacheName=" + cacheName + ", cacheKey=" + cacheKey);
            return false;
        }

        Cache cache = cacheManager.getCache(cacheName);
        if (null == cache) {
            log.error("#26 cache is null, cacheManager=" + cacheManager + ", cacheName=" + cacheName + ", cacheKey=" + cacheKey + ", cache=" + cache);
            return false;
        }

        return cache.remove(cacheKey);
    }

    public static Boolean cacheRemove(String cacheName, String cacheKey) {
        CacheManager cacheManager = getCacheManager();
        return cacheRemove(cacheManager, cacheName, cacheKey);
    }

    private static CacheManager getCacheManager() {
        BudoApplicationContextAware applicationContextAware = BudoApplicationContextAware.getInstanceNoNull();
        ApplicationContext applicationContext = applicationContextAware.getApplicationContext();
        String[] beanNames = applicationContext.getBeanNamesForType(CacheManager.class);
        if (null == beanNames || beanNames.length < 1) {
            log.error("#44 cacheManager not found, beanNames=" + beanNames);
            return null;
        }

        if (beanNames.length > 1) {
            log.error("#49 too many cacheManagers, beanNames=" + StringUtil.join(beanNames) // 
                    + ", applicationContext=" + applicationContext + ", applicationContextAware=" + applicationContextAware);
        }

        return (CacheManager) applicationContext.getBean(beanNames[0]);
    }
}